package com.rp.system.controller;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.rp.common.utils.JsonUtil;
import com.rp.common.utils.RpUtil;
import com.rp.common.vo.PageData;
import com.rp.controller.RpController;
import com.rp.system.po.Button;
import com.rp.system.service.ButtonService;

@Controller
@RequestMapping("/rp/system/buttonMng/")
public class ButtonController extends RpController {

	@Autowired
	private ButtonService buttonService;
	
	@RequestMapping("showButtonGrid")
	public ModelAndView showButtonGrid(){
		List<Record> rs = 
				Db.use("rpDb").find("select * from rp_system_buttons where moduleAlias = 'angl'"); 
		model.put("buttons", JSONArray.fromObject(RpUtil.jfinalListToList(rs)).toString());
		return forward("rp/system/buttonMng/buttonGrid.jsp");
	}
	
	@ResponseBody
	@RequestMapping("getButtonsByPage")
	public PageData getButtonsByPage(String moduleAlias){
		
		Page<Record> jfinalPage = Db.use("rpDb")
				.paginate(pageParam.getPageNumber(), pageParam.getPageSize(), "select *", 
						"from rp_system_buttons as b where moduleAlias = ?" + pageParam.getOrderBy("b"), moduleAlias);
		
		return new PageData(jfinalPage.getTotalRow(), RpUtil.jfinalPageToList(jfinalPage));
	}
	
	@ResponseBody
	@RequestMapping("getButtonsByModuleAlias")
	public List<Map<String, Object>> getButtonsByModuleAlias(String moduleAlias){
		List<Record> rs = Db.use("rpDb").find("select type,text,moduleId from rp_system_buttons where moduleId = ?", moduleAlias);
		return RpUtil.jfinalListToList(rs);
	}
	
	@ResponseBody
	@RequestMapping("saveButtons")
	public String saveButtons(String data, String moduleAlias){
		
		try {
			List<Button> btns = JsonUtil.jsonToList(data, "com.rp.system.po.Button");
			for (Button btn : btns) {
				if(btn.getId() == null){
					buttonService.addButton(btn, moduleAlias);
				}else{
					buttonService.updateButton(btn);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteButtons")
	public String deleteButtons(String data){
		try {
			List<Button> btns = JsonUtil.jsonToList(data, "com.rp.system.po.Button");
			for (Button btn : btns) {
				buttonService.deleteButton(btn);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
}
